package wensheng.stu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wensheng.stu.common.R;
import wensheng.stu.entity.User;
import wensheng.stu.service.UserService;
import wensheng.stu.utils.SMSUtils;
import wensheng.stu.utils.ValidateCodeUtils;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();

        if(phone!=null){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("code = {}",code);

//            SMSUtils.sendMessage("","","","");
            //将生成的验证码保存起来保存到session
            session.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }
        return R.error("短信发送失败");
    }

    //移动端用户登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        String phone = map.get("phone").toString();

        String code = map.get("code").toString();

        Object attribute = session.getAttribute(phone);

        if (attribute!=null&&attribute.equals(code)){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User one = userService.getOne(queryWrapper);

            if (one==null){
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user",one.getId());
            return R.success(one);

        }
        return R.error("登录失败");
    }
}
